package com.adopapa.ethexplorer.contoller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

import com.adopapa.ethexplorer.domain.TransactionInfo;
import com.adopapa.ethexplorer.service.ChaindataService;
import com.adopapa.ethexplorer.service.TransactionInfoService;
import com.adopapa.ethexplorer.utils.Tools;

import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/v1/tx")
public class TxController extends BaseController {

	@Autowired
	private ChaindataService chaindataService;
	@Autowired
	private TransactionInfoService transactionInfoService;

	/**
	 * 分页查询交易
	 */
	@GetMapping(path = "/transactions/{pageNo}", produces = MediaType.APPLICATION_JSON_VALUE)
	public Mono<Map<String, Object>> getTransactions(@PathVariable Integer pageNo,
			@RequestParam(required = false) Integer pageSize) {
		pageSize = Tools.empty(pageSize) ? 10 : pageSize;

		TransactionInfo transactionInfo = new TransactionInfo();
		Page<TransactionInfo> page = transactionInfoService.getTransactionInfoPage(pageNo, pageSize, transactionInfo);
		return Mono.just(ok(page));
	}

	@GetMapping(path = "/transaction/{hash}", produces = MediaType.APPLICATION_JSON_VALUE)
	public Mono<Map<String, Object>> getTransaction(@PathVariable String hash) {
		TransactionInfo transactionInfo = transactionInfoService.getTransactionInfoByHash(hash);
		return Mono.just(ok(transactionInfo));
	}

	@GetMapping(path = "/receipt/{hash}", produces = MediaType.APPLICATION_JSON_VALUE)
	public Mono<Map<String, Object>> getPendingTxHash(@PathVariable String hash) {
		TransactionReceipt receipt = chaindataService.getTransactionReceipt(hash);
		return Mono.just(ok(receipt));
	}

}
